import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { Button, message } from 'antd';
import { ModalForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';
import { add, test } from '../service';


const CreateForm = (props, ref) => {

  /** 新建窗口的弹窗 */
  const [createModalVisible, handleCreateModalVisible] = useState(false);
  /** 绑定form表单 */
  const formRef = useRef();
  /** 传递参数默认值 */
  const defaultParam = '{"headers":{},"values":{}}'

  // react规定必须使用useImperativeHandle方法，
  // 来保存并抛出想要传递给父组件的方法或者数据，
  // 第一个参数是ref,第二个参数是函数，返回想要抛出的对象集合
  useImperativeHandle(ref, () => ({
    handleCreateModalVisible,
  }));

  /**
   * 测试数据源
   */
  const handleTest = async () => {
    const hide = message.loading('正在测试');
    try {
      const formValue = formRef.current.getFieldsValue();
      if(formValue.params){
        formValue.params = JSON.parse(formValue.params);
      }
      const value = await test(formValue);
      if(value.success){
        hide();
        message.success("测试成功");
      }else{
        message.error(value.errorMessage);
      }
      return true;
    } catch (error) {
      hide();
      message.error('测试失败');
      return false;
    }
  };


  /**
   * 添加
   *
   * @param fields
   */
  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      if(fields.params){
        fields.params = JSON.parse(fields.params);
      }
      await add({ ...fields });
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  return (
    <ModalForm
      formRef={formRef}
      title="新建数据源"
      width="50%"
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              key="test"
              onClick={() => {
                handleTest();
              }}
            >
              测试
            </Button>,
          ];
        },
      }}
      visible={createModalVisible}
      onFinish={async (value) => {
        const success = await handleAdd(value);

        if (success) {
          handleCreateModalVisible(false);

          if (props.actionRef.current) {
            props.actionRef.current.reload();
          }
        }
      }}
      onVisibleChange={handleCreateModalVisible}
    >
      <ProFormText
        width="90%"
        label="数据源名称"
        name="sourceName"
        rules={[
          {
            required: true,
            message: '请输入数据源名称',
          },
        ]}
        placeholder="数据源的名称"
      />
      <ProFormSelect
        label="数据源类型"
        name="sourceType"
        rules={[
          {
            required: true,
            message: '请选择数据源类型',
          },
        ]}
        options={[
          {
            label: 'MYSQL',
            value: 'MYSQL',
          },
          {
            label: 'HTTP',
            value: 'HTTP',
          },
        ]}
      />
      <ProFormTextArea
        width="90%"
        label="连接地址"
        name="url"
        rules={[
          {
            required: true,
            message: '请输入连接地址',
          },
        ]}
        placeholder="连接地址"
      />
      <ProFormText
        width="90%"
        label="用户名(数据库必填)"
        name="username"
        placeholder="数据库用户名"
      />
      <ProFormText

        width="90%"
        label="密码(数据库必填)"
        name="password"
        placeholder="数据库密码"
      />
      <ProFormTextArea
        width="90%"
        label="请求参数(HTTP接口,不填保持默认)"
        name="params"
        placeholder="请求参数"
        initialValue={defaultParam}
      />
      <ProFormSelect
        label="状态"
        name="state"
        rules={[
          {
            required: true,
            message: '请选择数据源类型',
          },
        ]}
        options={[
          {
            label: '启用',
            value: '1',
          },
          {
            label: '关闭',
            value: '0',
          },
        ]}
      />
      <ProFormTextArea
        width="90%"
        label="备注"
        name="remark"
        placeholder="备注信息"
      />
    </ModalForm>
  );
};

export default forwardRef(CreateForm);
